package com.project.easy.common.db.mybatisplus.core.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import  com.project.easy.common.util.collection.CollectionUtil;
import  com.project.easy.common.util.util.ConvertObjectToString;
import com.project.easyt.common.db.common.config.DbConfig;
import com.project.easyt.common.db.common.config.ReadDbConfig;
import com.project.easyt.common.db.common.config.WriteDbConfig;
import com.project.easyt.common.db.common.core.IDynamicDataSourceEx;
import com.project.easyt.common.db.common.core.spring.DynamicDataSource;
import com.project.easyt.common.db.common.enums.DbEnums;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2020/9/27 16:25
 * @description: 读数据库属性配置
 */
@Configuration
@ConditionalOnProperty(prefix = "yqkj.zysoft.db", name = "open", matchIfMissing = false, havingValue = "true")
public class MybatisplusConfig implements ApplicationContextAware {
    /**
     * 上下文
     */
    private  ApplicationContext applicationContext;

    /**
     * @return 返回数据库配置
     * @throws Exception 数据库异常
     */
    @Bean
    @ConditionalOnBean(value = {ReadDbConfig.class, WriteDbConfig.class})
    public DynamicDataSource initDynamicDataSource() throws Exception {
        ReadDbConfig dbConfig = this.applicationContext.getBean(ReadDbConfig.class);
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Properties properties = initProperties(dbConfig);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        WriteDbConfig writeDbConfig = this.applicationContext.getBean(WriteDbConfig.class);
        Properties write = initProperties(writeDbConfig);
        DataSource writeDataSource = DruidDataSourceFactory.createDataSource(write);
        Map<Object, Object> dataSourceMap = new HashMap<>(20);
        dataSourceMap.put(DbEnums.WRITE.getCode(), writeDataSource);
        dataSourceMap.put(DbEnums.READ.getCode(), dataSource);
        Map<String, IDynamicDataSourceEx> beansOfType = this.applicationContext.getBeansOfType(IDynamicDataSourceEx.class);
        if (!CollectionUtil.isNull(beansOfType)) {
            beansOfType.forEach((k, dataSourceService) -> {
                Map<String, DataSource> excute = dataSourceService.excute();
                if (!CollectionUtil.isNull(excute)) {
                    dataSourceMap.putAll(excute);
                }
            });
        }
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        dynamicDataSource.setDefaultTargetDataSource(dataSource);
        return dynamicDataSource;
    }
    /**
     * 数据库属性配置
     * @param dbConfig 数据库配置
     * @return 返回属性配置
     */
    private Properties initProperties(DbConfig dbConfig) {
        Properties properties = new Properties();
        properties.put("name", String.format("yqkj_%s", dbConfig.getUsername()));
        properties.put("username", dbConfig.getUsername());
        properties.put("password", dbConfig.getPassword());
        properties.put("url", dbConfig.getUrl());
        properties.put("filters", dbConfig.getFilters());
        properties.put("maxWait", ConvertObjectToString.convert(dbConfig.getMaxWait()));
        properties.put("maxActive",  ConvertObjectToString.convert(dbConfig.getMaxActive()));
        properties.put("minIdle", ConvertObjectToString.convert(dbConfig.getMinIdle()));
        properties.put("timeBetweenEvictionRunsMillis", ConvertObjectToString.convert(dbConfig.getTimeBetweenEvictionRunsMillis()));
        properties.put("minEvictableIdleTimeMillis", ConvertObjectToString.convert(dbConfig.getMinEvictableIdleTimeMillis()));
        properties.put("validationQuery", dbConfig.getValidationQuery());
        properties.put("testWhileIdle",  ConvertObjectToString.convert(dbConfig.getTestWhileIdle()));
        return properties;
    }

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    /**
     * 注册一个StatViewServlet    druid监控页面配置1-帐号密码配置
     * @return servlet registration bean
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<>(
                new StatViewServlet(), "/druid/*");
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "yqkj123");
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    /**
     * 注册一个：filterRegistrationBean   druid监控页面配置2-允许页面正常浏览
     * @return filter registration bean
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> druidStatFilter() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(
                new WebStatFilter());
        // 添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}
